package cn.tedu.route;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.Scanner;

public class RouteConsumer {
    public static void main(String[] args) throws Exception{
        //1.配置连接信息
        ConnectionFactory cf = new ConnectionFactory();
        cf.setHost("127.0.0.1");
        cf.setPort(5672);//5672是默认端口，可以省略
        cf.setUsername("guest");
        cf.setPassword("guest");
        //2.创建tcp连接对象
        Connection nc = cf.newConnection();
        //3.创建channel
        Channel cc = nc.createChannel();
        //4.定义direct类型的交换机
        cc.exchangeDeclare("route_exchange", BuiltinExchangeType.DIRECT);
        //5.定义队列
        String queueName = cc.queueDeclare().getQueue();
        //6.队列和交换机支持多关键字绑定
        System.out.print("输入绑定关键字，用空格隔开:");
        String str = new Scanner(System.in).nextLine();
        String[] bindingKeys = str.split("\\s+");
        for (String bindingKey : bindingKeys) {
            cc.queueBind(queueName,"route_exchange",bindingKey);
        }
        //处理数据的回调函数
        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String s, Delivery delivery) throws IOException {
                //消息封装在Delivery对象中
                byte[] body = delivery.getBody();
                String msg = new String(body);
                System.out.println("接收到消息："+msg);
                //处理msg的操作
                //遍历msg。遇到一个'.'就休息1s
                for (int i = 0; i < msg.length(); i++) {
                    if(msg.charAt(i)=='.'){
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
                System.out.println("消息处理完毕");
            }
        };
        //取消接收时的回调函数
        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String s) throws IOException {

            }
        };
        cc.basicConsume(queueName,true,deliverCallback,cancelCallback);
    }
}
